%---------- information ------------------------------
% finds the overlap between two rts files using unique time Id
% packs the reference fileds also to the main matrix
% trims nonoverlap section and/or end points < block*nfft
% this program uses IsOver.m as subroutines
% trying to club this routine with rr estimator  18.07.2002
% this routine now finds the overlap, create a new TS structure
% with channels from two sites with filter infor etc
% 
% latest date 31.10.2002

function[TSc,er,len] = RrCorrectTS(TS,TSr,ProcDef),

er=1;
sample = ProcDef.GMS05.fs(ProcDef.nband);

AA  = size(TS.matrix);
StA = TS.head.StID;
nbA = TS.head.band;

BB = size(TSr.matrix);
nbB = TSr.head.band;
StB = TSr.head.StID;

%---------- declaration -------------------------------

block = ProcDef.block;
lengthA = AA(1)/block;   % sample
lengthB = BB(1)/block;	% sample

EnA = StA + (lengthA*block)/sample;
EnB = StB + (lengthB*block)/sample;

%--------checking validity------------------

flag = IsOver(StA,EnA,StB,EnB);

if nbA ~= nbB,
   er=-1;
return;
end;

if flag~=1,
er=-2;
return;
end;
%----------- finding out overlap ----------------------

if StA > StB,
offsetB = (StA-StB);
offsetA = 0;
elseif StA < StB,
offsetA = (StB-StA);
offsetB = 0;
elseif StA == StB,
offsetA = 0;
offsetB = 0;
end;

if EnA > EnB,
EndAll = EnB;
elseif EnA < EnB,
EndAll = EnA;
elseif EnA == EnB,
EndAll = EnA;
end;

%------------------------------

len = floor(((EndAll - (StB + offsetB))*sample )/block); 

if len < 1,
er=-3;   
end;
offsetA=floor(offsetA*sample);
offsetB=floor(offsetB*sample);

a1=find(ProcDef.notchdef==1);
a2=find(ProcDef.notchdef==2);
b1=ProcDef.sensor(a1);
b2=ProcDef.sensor(a2);

TSc.matrix(:,a1) = TS.matrix(1+offsetA:offsetA+len*block,b1); % changed 31.10.2002
TSc.matrix(:,a2) = TSr.matrix(1+offsetB:offsetB+len*block,b2); % 2+ and block+1 business for rr phase problem
TSc.head=TS.head; %to get site ID & Location from parent site
TSc.head.nchannel = length(ProcDef.sensor);
TSc.probe.dist=[TS.probe.dist(b1) TSr.probe.dist(b2)];
TSc.probe.gain=[TS.probe.gain(b1) TSr.probe.gain(b2)];
TSc.filter.Filt=[TS.filter.Filt'; TSr.filter.Filt']';
TSc.filter.NotchF=[TS.filter.NotchF'; TSr.filter.NotchF']';

